<template>
  <el-dialog :visible.sync="dialogShow" title="分配权限" @close="close">
    <!--
        只要给tree加上show-checkbox就会有多选框
     -->
    <el-tree
      ref="tree"
      :data="treeData"
      :props="props"
      node-key="id"
      show-checkbox
      default-expand-all
      check-strictly
      :default-checked-keys="checkList"
    />

    <div style="text-align:center;">
      <el-button size="small" @click="dialogShow = false">取消</el-button>
      <el-button size="small" type="primary" @click="save">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { permListAPI } from '@/api/permissions'
import { roleDetailAPI, assignPermAPI } from '@/api/role'
import { array2Tree } from '@/utils'
export default {
  data() {
    return {
      dialogShow: false,
      props: {
        label: 'name',
        children: 'children'
      },
      treeData: [],
      checkList: [],
      id: ''
    }
  },
  methods: {

    close() {
      // 关闭时清空选中的效果
      this.$refs.tree.setCheckedKeys([])
    },

    async show(id) {
      this.id = id
      // 1. 加载出所有的数据---转树
      const res = await permListAPI()
      this.treeData = array2Tree(res.data, '0')

      // 2. 根据角色id获取角色的详情
      const res2 = await roleDetailAPI(id)
      this.checkList = res2.data.permIds

      // 3. 显示出对话框
      this.dialogShow = true

      // this.$nextTick(() => {
      //   this.$refs.tree.setCheckedKeys(res2.data.permIds)
      // })
    },

    async save() {
      // console.log(this.$refs.tree.getCheckedKeys())
      await assignPermAPI({
        // 角色id
        id: this.id,
        // 拿到选中的权限的id，组成数组
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('分配成功')
      this.dialogShow = false
    }
  }
}
</script>

<style></style>
